
package com.dps.omc.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dps.omc.enumer.EnumSubjectState;
import com.dps.omc.model.*;
import com.dps.omc.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dps.common.domain.view.BizData4Page;
import com.dps.common.utils.IdGenerator;
import com.dps.common.utils.JsonResult;
import com.dps.common.utils.PageParam;
import com.dps.common.utils.Constants;

@Controller
public class SubjectAction extends AbstractAdminController<ISubjectService>{

    @Autowired
    private ISubjectService subjectService;
    @Autowired
    private IBizTypeService bizTypeService;
    @Autowired
    private IBizUnitService bizUnitService;
    @Autowired
    private ISubjectArtifactService subjectArtifactService;
    @Autowired
    private ISubjectBizTypeService subjectBizTypeService;
    @Autowired
    private ISubjectBizUnitService subjectBizUnitService;
    @Autowired
    private IUploadFormatService uploadFormatService;
    @Autowired
    private IUserBizUnitService userBizUnitService;
    @Autowired
    private IUserBizTypeService userBizTypeService;
    
    @RequestMapping(value="/subject/list")
    public String list(Subject subject,ModelMap model,PageParam pageParam,HttpServletRequest request,HttpServletResponse response){

        //获取参数
    	Map<String, Object> conditions = getQueryMap(subject); 	
    	BizData4Page<Subject> pageCtx = doPage(model, conditions, pageParam);
    	model.addAttribute("subject", subject);
    	return "/module/subject/list";
    }    
    
    @RequestMapping(value="/subject/add")
    public String add(ModelMap model,HttpServletRequest request,HttpServletResponse response){

//        List<BizType> bizTypes = bizTypeService.findAll();
//        List<BizUnit> bizUnits = bizUnitService.findAll();

        User user = getCurrentUser();
        List<BizType> bizTypes = bizTypeService.findListByUserRights(user.getId());
        List<BizUnit> bizUnits = bizUnitService.findListByUserRights(user.getId());

        model.addAttribute("bizTypes", bizTypes);
        model.addAttribute("bizUnits", bizUnits);
    	model.addAttribute("subject", new Subject());
        model.addAttribute("uploadFormats",uploadFormatService.findAll());
        return "module/subject/edit";
    }    
    
    @RequestMapping(value="/subject/edit")
    public String edit(String id,ModelMap model,HttpServletRequest request,HttpServletResponse response){
    	
    	Subject subject = subjectService.fetch(id);
//        List<BizType> bizTypes = bizTypeService.findAll();
//        List<BizUnit> bizUnits = bizUnitService.findAll();

        User user = getCurrentUser();
        List<BizType> bizTypes = bizTypeService.findListByUserRights(user.getId());
        List<BizUnit> bizUnits = bizUnitService.findListByUserRights(user.getId());

//        List<SubjectArtifact> subjectArtifacts = subjectArtifactService.findList("subjectId", id);
        List<SubjectArtifact> subjectArtifacts = subjectArtifactService.findListBySubjectId(id);
        List<SubjectBizUnit> subjectBizUnits = subjectBizUnitService.findList("subjectId",id);
        List<SubjectBizType> subjectBizTypes = subjectBizTypeService.findList("subjectId",id);
        model.addAttribute("bizTypes", bizTypes);
        model.addAttribute("bizUnits", bizUnits);
    	model.addAttribute("subject", subject);
        model.addAttribute("subjectArtifacts", subjectArtifacts);
        model.addAttribute("subjectBizTypeMap", this.getSubjectBizTypeMap(subjectBizTypes));
        model.addAttribute("subjectBizUnitMap", this.getSubjectBizUnitMap(subjectBizUnits));
        model.addAttribute("uploadFormats",uploadFormatService.findAll());
        return "module/subject/edit";
    }

    private Map<String,String> getSubjectBizTypeMap(List<SubjectBizType> subjectBizTypes)
    {
        Map<String,String> map = new HashMap<>();
        for(SubjectBizType subjectBizType:subjectBizTypes)
        {
            map.put(subjectBizType.getBizType(),subjectBizType.getBizType());
        }
        return map;
    }

    private Map<String,String> getSubjectBizUnitMap(List<SubjectBizUnit> subjectBizUnits)
    {
        Map<String,String> map = new HashMap<>();
        for(SubjectBizUnit subjectBizUnit:subjectBizUnits)
        {
            map.put(subjectBizUnit.getBizUnit(),subjectBizUnit.getBizUnit());
        }
        return map;
    }
    
    @RequestMapping(value="/subject/save")
    @ResponseBody
    public String save(HttpServletRequest request,Subject subject){
		boolean isAddNew = StringUtils.isBlank(subject.getId())?true:false;
        String[] artifactIdArray = request.getParameterValues("artifactIdArray");
        String[] bizUnitArray = request.getParameterValues("bizUnitArray");
        String[] bizTypeArray = request.getParameterValues("bizTypeArray");
        String[] isDeploy = request.getParameterValues("isDeploy");
        List<String> bizTypes = new ArrayList<String>();
        List<String> bizUnits = new ArrayList<String>();
        List<String> artifactIds = new ArrayList<String>();
        List<SubjectArtifact> subjectArtifacts = new ArrayList<>();
        if(bizUnitArray!=null)
        {
            for(String bizUnit:bizUnitArray)
            {
                bizUnits.add(bizUnit);
            }
        }

        if(bizTypeArray!=null)
        {
            for(String bizType:bizTypeArray)
            {
                bizTypes.add(bizType);
            }
        }

        if(artifactIdArray!=null)
        {
            for(String artifactId:artifactIdArray)
            {
                artifactIds.add(artifactId);
            }
            for(int i=0;i<artifactIdArray.length;i++)
            {
                SubjectArtifact subjectArtifact = new SubjectArtifact();
                subjectArtifact.setArtifactId(artifactIdArray[i]);
                subjectArtifact.setIsDeploy(Integer.parseInt(isDeploy[i]) > 0 ? true : false);
                subjectArtifacts.add(subjectArtifact);
            }
        }

		if(isAddNew)
		{
			subject.setId(IdGenerator.createNewId());
            subject.setStatus(EnumSubjectState.NEW);
            User user = getCurrentUser();
            subject.setCreaterId(user.getId());
            subject.setCreaterName(user.getRealName());
			subjectService.create(subject, bizTypes, bizUnits);
            subjectArtifactService.create(subject.getId(),subjectArtifacts);
		}
		else
		{
            subjectService.update(subject, bizTypes, bizUnits);
            subjectArtifactService.create(subject.getId(),subjectArtifacts);
		}
        return JsonResult.saveSuccessClose(Constants.MAIN_TAB).toString();
    }    
    
    @RequestMapping(value="/subject/delete")
    @ResponseBody
    public String delete(String ids,HttpServletRequest request){
    	
    	subjectService.deleteByIds(ids);
    	return JsonResult.DELETE_SUCCESS.toString();
    }

    //将已创建的作业状态更改为已创建
    @RequestMapping(value="/subject/editStatus")
    @ResponseBody
    public String editStatus(String sid,HttpServletRequest request) {
//        //Subject subject = new Subject();
//        int count = subjectService.editStatus(sub_id);
//        subject.setId("*********"+sub_id);
//        System.out.println(sub_id);
//        if (count == 1) {//job表里和subject表里有共同的id值，就改变状态为已创建
//            subject.setStatus(EnumSubjectState.DEPLOYED);
//            System.out.println("*********"+subject);
//            subjectService.update(subject);
//        }
//        return JsonResult.EDIT_STATUS.toString();
//        /*else  if(status.equals("CREATE")){//若状态已更改为创建，再次改变时给出状态已更改提示
//
//            return JsonResult.JOB_CREATE.toString();
//        }else{
//            return JsonResult.JOB_STATUS.toString();//若作业尚未创建，改状态给出提示该作业尚未创建
//        }*/

        Subject subject = subjectService.fetch(sid);
        subject.setStatus(EnumSubjectState.DEPLOYED);
        subjectService.update(subject);
        return JsonResult.operateSuccess(Constants.MAIN_TAB).toString();
    }

    protected Map getQueryMap(Subject subject)
    {
        Map<String, Object> conditions = new HashMap();

        conditions.put("subjectNo", subject.getSubjectNo());
        conditions.put("reason", subject.getReason());
        conditions.put("updateLog", subject.getUpdateLog());
        conditions.put("accountNote", subject.getAccountNote());
        conditions.put("financeNote", subject.getFinanceNote());
        conditions.put("updateAdvice", subject.getUpdateAdvice());
        conditions.put("updateMethod", subject.getUpdateMethod());
        conditions.put("status", subject.getStatus());
        conditions.put("note", subject.getNote());
        conditions.put("createrId", subject.getCreaterId());
        conditions.put("createrName", subject.getCreaterName());
        conditions.put("createDate", subject.getCreateDate());
        return conditions;
    }

    @RequestMapping(value="/subject/listbymanager")
    public String listByManager(Subject subject,ModelMap model,PageParam pageParam,HttpServletRequest request,HttpServletResponse response){

        //获取参数
        User user = getCurrentUser();
        Map<String, Object> conditions = getQueryMap(subject);
        conditions.put("createrId",user.getId());
        BizData4Page<Subject> pageCtx = doPage(model, conditions, pageParam);
        model.addAttribute("subject", subject);
        return "/module/subject/listbymanager";
    }

    @Override
    protected ISubjectService getMainService() {
        return subjectService;
    }

    @Override
    protected String getMainObjName() {
        return "subject";
    }

    @Override
    protected String getViewTitle() {
        return "subject";
    }
}
